package com.cskaoyan.batch;

import com.cskaoyan.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 创建日期: 2022/03/22 14:35
 *
 * @author ciggar
 *
 * 批处理
 *
 * 业务场景：批量插入数据  t_user
 */
public class BatchDemo {

    static Connection connection;
    static Statement statement;

    static {
        // 获取连接
        connection = JDBCUtils.getConnection();

        try {
            statement = connection.createStatement();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws SQLException {
//        long t1 = System.currentTimeMillis();
//        statementFor();
//        long t2 = System.currentTimeMillis();
//        statementBatch();
        long t3 = System.currentTimeMillis();
        prePareStatementBatch();
        long t4 = System.currentTimeMillis();


//        System.out.println("statementFor:" + (t2-t1) + " ms");
//        System.out.println("statementBatch:" + (t3-t2) + " ms");
        System.out.println("prePareStatementBatch:" + (t4-t3) + " ms");

    }





    // 使用statement循环
    public static void statementFor() throws SQLException {


        for (int i = 0; i < 10000; i++) {
            int affectedRows = statement.executeUpdate("insert into t_user values (null,'statementFor',null,null)");
        }


    }




    // 使用statement批处理
    public static void statementBatch() throws SQLException {


        for (int i = 0; i < 10000; i++) {

            statement.addBatch("insert into t_user values (null,'statementBatch',null,null)");
        }

        statement.executeBatch();

    }


    // 使用PrepareStatement批处理
    public static void prePareStatementBatch() throws SQLException {

        PreparedStatement preparedStatement = connection.prepareStatement("insert into t_user values (null,?,null,null)");

        for (int i = 0; i < 1000000; i++) {
            String name = "zs" + ":" + i;
            preparedStatement.setString(1,name);
            preparedStatement.addBatch();

        }
        preparedStatement.executeBatch();


    }




}
